<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :size="size" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类名称" prop="gTypeName">
        <el-input
          v-model="queryParams.gTypeName"
          placeholder="请输入分类名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="首页推荐" prop="homeShow">
        <el-select v-model="queryParams.homeShow" placeholder="首页推荐状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="展示" prop="delFlag">
        <el-select v-model="queryParams.delFlag" placeholder="展示状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_show_hide"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
	      <el-button icon="el-icon-search" class="query-btn" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" class="reset-btn"  @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          class="add-btn"
          plain
          icon="el-icon-plus"
          :size="size"
          @click="handleAdd"
          v-hasPermi="['goods:type:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          class="expand-btn"
          plain
          icon="el-icon-sort"
          :size="size"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      border stripe
      :data="typeList"
      row-key="gTypeId"
      :size="size"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column label="分类名称" header-align="center" prop="gTypeName" />
      <el-table-column label="分类图片" align="center" prop="imagePath" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="分类备注" align="center" prop="remark" />
      <el-table-column label="显示顺序" align="center" prop="orderNum" />
      <el-table-column label="首页推荐" align="center" prop="homeShow">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.homeShow"
            active-value="Y"
            inactive-value="N"
            @change="handleHomeShowChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="显示状态" align="center" prop="delFlag">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.delFlag"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center" prop="updateBy" />
      <el-table-column label="操作时间" align="center" prop="updateTime" width="160" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            class="add-btn"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['goods:type:add']"
          >新增</el-button>
          <el-button
            class="edit-btn"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['goods:type:edit']"
          >修改</el-button>
          <el-button
            class="del-btn"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['goods:type:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改商品类型对话框 -->
    <el-dialog :title="title" :size="size" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="18">
            <el-form-item label="上级分类" prop="parentId">
              <treeselect v-model="form.parentId" :options="typeOptions" :normalizer="normalizer" placeholder="请选择父类型id" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="显示顺序" prop="orderNum">
              <el-input v-model="form.orderNum" placeholder="请输入显示顺序" type="number" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="分类名称" prop="gTypeName">
          <el-input v-model="form.gTypeName" placeholder="请输入类型名称" />
        </el-form-item>
        <el-form-item label="封面图片" prop="image">
          <el-button @click="openSelectImage" class="select-btn" plain>选择图片</el-button>
          <div style="width: 200px; display: inline-grid; margin-left: 30px;">
            <image-upload ref="uploadImage" v-if="form.image" v-model="form.image" :auto-upload="false" :limit="1" :isShowTip = false
                          @success="handleImageSuccess" style="width: 500px;" disabled />
          </div>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="首页推荐" prop="homeShow">
              <el-radio-group v-model="form.homeShow">
                <el-radio
                  v-for="dict in dict.type.sys_yes_no"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示状态" prop="delFlag">
              <el-radio-group v-model="form.delFlag">
                <el-radio
                  v-for="dict in dict.type.sys_show_hide"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="包含属性">
          <el-checkbox v-model="attrExpand" @change="handleCheckedTreeExpand($event)">展开/折叠</el-checkbox>
          <el-checkbox v-model="attrNodeAll" @change="handleCheckedTreeNodeAll($event)">全选/全不选</el-checkbox>
          <!-- <el-checkbox v-model="attrCheckStrictly" @change="handleCheckedTreeConnect($event)">父子联动</el-checkbox> -->
          <el-button class="config-btn" @click="getParentAttrs" :disabled="!form.parentId" style="margin-left: 10px;" >获取父属性</el-button>
          <el-tree
            class="tree-border"
            :data="options.attrOptions"
            show-checkbox
            ref="attr"
            node-key="id"
            :check-strictly="!attrCheckStrictly"
            empty-text="加载中，请稍候"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="save-btn" @click="submitForm">确 定</el-button>
        <el-button class="cancel-btn" @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

<!--    <image-select ref="select" :params="{ imageType: '7' }" @ok="handleSelectOk" />-->

    <select-image ref="select" :params="{ imageType: '7' }" @ok="handleSelectOk" />

  </div>
</template>

<script>
import { listType, getType, delType, addType, updateType, findMaxOrderNum, updateStatus } from '@/api/goods/type'
import { treeSelect as attrTreeselect, typeAttrTreeSelect as getTypeAttrTreeSelect } from "@/api/goods/attr";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import ImageSelect from '@/views/goods/images/components/selectImage.vue'
import SelectImage from '@/views/goods/images/components/select.vue'

export default {
  name: "Type",
  dicts: ['sys_normal_disable', 'sys_yes_no', 'sys_show_hide'],
  components: {
    ImageSelect, SelectImage,
    Treeselect
  },
  computed: {
    size() {
      return this.$store.getters.size
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 商品类型表格数据
      typeList: [],
      // 商品类型树选项
      typeOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 属性树是否展开
      attrExpand: true,
      // 属性树全选/不选
      attrNodeAll: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      //
      attrCheckStrictly: true,
      // 查询参数
      queryParams: {
        gTypeName: null,
        homeShow: null,
        delFlag: null
      },
      // 表单参数
      form: {},
      options: {
        attrOptions: []
      },
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 表单校验
      rules: {
        gTypeName: [
          { required: true, message: "类型名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询商品类型列表 */
    getList() {
      this.loading = true;
      listType(this.queryParams).then(response => {
        this.typeList = this.handleTree(response.data, "gTypeId", "parentId");
        this.loading = false;
      });
    },
    /** 转换商品类型数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.gTypeId,
        label: node.gTypeName,
        children: node.children
      };
    },
	  /** 查询商品类型下拉树结构 */
    getTypeTreeselect() {
      listType().then(response => {
        this.typeOptions = [];
        const data = { gTypeId: 0, gTypeName: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "gTypeId", "parentId");
        this.typeOptions.push(data);
      });
    },
    /** 查询菜单树结构 */
    getAttrTreeselect() {
      attrTreeselect().then(response => {
        this.options.attrOptions = response.data;
      });
    },
    getTypeAttrTreeSelect(typeId) {
      return getTypeAttrTreeSelect(typeId).then(res => {
        this.options.attrOptions = res.attrs;
        return res;
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset(orderNum) {
      if (this.$refs.attr != undefined) {
        this.$refs.attr.setCheckedKeys([]);
      }
      this.menuExpand = false,
      this.menuNodeAll = false,
      this.attrCheckStrictly = true,
      this.form = {
        gTypeId: null,
        parentId: null,
        gTypeName: null,
        homeShow: 'N',
        image: null,
        orderNum: orderNum ? orderNum : null,
        delFlag: '0',
        remark: null,
        attrIds: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.form.homeShow = '';
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      let parentId = 0;
      if (row && row.gTypeId) {
        parentId = row.gTypeId;
      }
      findMaxOrderNum(parentId).then(res => {
        this.reset(res.data);
        this.getTypeTreeselect();
        this.getAttrTreeselect();
        if (row != null && row.gTypeId) {
          this.form.parentId = row.gTypeId;
        } else {
          this.form.parentId = 0;
        }
        this.open = true;
        this.title = "添加商品类型";
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTypeTreeselect();
      const typeAttr = this.getTypeAttrTreeSelect(row.gTypeId);
      if (row != null) {
        this.form.parentId = row.parentId;
      }
      getType(row.gTypeId).then(response => {
        this.form = response.data;
        this.open = true;
        this.$nextTick(() => {
          typeAttr.then((res) => {
            let checkedKeys = res.checkedKeys
            checkedKeys.forEach((v) => {
                this.$nextTick(()=>{
                    this.$refs.attr.setChecked(v, true ,false);
                })
            })
          })
        })
        this.title = "修改商品类型";
      });
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.attr.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.attr.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.attrIds = this.getMenuAllCheckedKeys();
          if (this.form.gTypeId != null) {
            updateType(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addType(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除商品类型名称为 "' + row.gTypeName + '" 的数据项？').then(function() {
        return delType(row.gTypeId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value) {
      let attrList = this.options.attrOptions;
      for (let i = 0; i < attrList.length; i++) {
        this.$refs.attr.store.nodesMap[attrList[i].id].expanded = value;
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value) {
      this.$refs.attr.setCheckedNodes(value ? this.options.attrOptions: []);
    },
    // 获取父类型节点属性
    getParentAttrs() {
      let parentId = '0';
      if (this.form && this.form.parentId) {
        parentId = this.form.parentId;
      }
      this.getTypeAttrTreeSelect(parentId).then(res => {
            let checkedKeys = res.checkedKeys
            checkedKeys.forEach((v) => {
                this.$nextTick(()=>{
                    this.$refs.attr.setChecked(v, true ,false);
                })
            })
      });
    },
    handleHomeShowChange(row) {
      let text = row.homeShow === "Y" ? "启用" : "停用";
      this.$modal.confirm('确认要 ' + text + ' 分类 <' + row.gTypeName + '> 的首页推荐分类吗？').then(function() {
        return updateStatus({ homeShow: row.homeShow, gTypeId: row.gTypeId });
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.homeShow = row.homeShow === "Y" ? "N" : "Y";
      });
    },

    handleStatusChange(row) {
      let text = row.delFlag === "0" ? "显示" : "隐藏";
      this.$modal.confirm('确认要 ' + text + ' 分类 <' + row.gTypeName + '> 的分类吗？').then(function() {
        return updateStatus({ delFlag: row.delFlag, gTypeId: row.gTypeId });
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.delFlag = row.delFlag === "0" ? "1" : "0";
      });
    },
    /** 打开授权用户表弹窗 */
    openSelectImage() {
      this.$refs.select.show();
    },
    /** 选择图片后 */
    handleSelectOk(val) {
      if (val && val.length === 1) {
        const image = val[0];
        this.form.imageId = image.imageId;
        this.form.image = image.imagePath;
      }
    },
  }
};
</script>
<style scoped>
::v-deep .el-table .el-table__body-wrapper .el-table__cell {
  padding: 5px 0 2px 0;
}
.http-image-list {
  height: 100px;
  margin-right: 18px;
}
</style>
